package com.kehutong.wwin.service.service;

import com.kehutong.common.tencent.AesException;
import com.kehutong.wwin.service.entity.Corp;
import com.kehutong.wwin.service.entity.Suite;
import com.kehutong.wwin.service.util.WwInHttpClient;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.CallBack;
import org.coraframework.util.Objects;

import java.time.LocalDateTime;

@WebService("/wwin/corp")
public class CorpService {
	private static final Logger logger = LoggerFactory.getLogger(CorpService.class);
	
	@Inject
	private JdbcSession jdbcSession;
	@Inject
	private WwInHttpClient httpClient;

	
	@ReqMapping("/getConfig")
    public Object getDecEncryptConfig(JSONObject wwJson) throws AesException {
        Corp corp = jdbcSession.findById(Corp.class, wwJson.getString("corpId"));

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("khtId", corp.getKhtid());
        jsonObject.put("employeeToken", corp.getEmployeeToken());
        jsonObject.put("employeeEncodingAESKey", corp.getEmployeeEncodingAESKey());
        jsonObject.put("contactToken", corp.getContactToken());
        jsonObject.put("contactEncodingAESKey", corp.getContactEncodingAESKey());

        return jsonObject;
    }

    /**
     * 通过khtId获取Corp
     *
     * @param khtId
     * @return
     */
    @ReqMapping("/getCorpId")
    public Corp getCropByKhtId(String khtId) {
        return jdbcSession.findOne(Corp.class)
                .eq("khtid", khtId)
                .eq("deleted", false)
                .exe();
    }

	/**
	 * 返回联系人token
	 * @param corp
	 * @return
	 * @throws Exception
	 */
	public String getContactAccessToken(Corp corp) throws Exception {
		if(logger.isInfoEnabled()){
			logger.info("getContactAccessToken:企业微信联系人Token失效时间 is: {}",corp.getContactAccessTokenExpiredTime());
		}
		if (valid(corp.getContactAccessTokenExpiredTime())) {
			if(logger.isInfoEnabled()) {
				logger.info("getContactAccessToken:企业微信联系人Token时间没有失效,contactAccessToken is: {}",corp.getContactAccessToken());
			}
			return corp.getContactAccessToken();
		}
		
		getAccessToken(corp.getId(), corp.getContactSecret(), json -> {
			corp.setContactAccessToken(json.getString("access_token"));
			corp.setContactAccessTokenExpiredTime(LocalDateTime.now().plusSeconds(json.getLong("expires_in")));
			jdbcSession.updateById(corp);
			if(logger.isDebugEnabled()){
				logger.debug("回调更新企业联系人Token信息,Corp: {}",corp);
			}
		});

		return corp.getContactAccessToken();
	}

	/**
	 * 返回员工token
	 * @param corp
	 * @return
	 * @throws Exception
	 */
	public String getEmployeeAccessToken(Corp corp) throws Exception {
		if(logger.isInfoEnabled()){
			logger.info("getEmployeeAccessToken:企业微信员工Token时间 is: {}",corp.getEmployeeAccessTokenExpiredTime());
		}
		if (valid(corp.getEmployeeAccessTokenExpiredTime())) {
			logger.info("getEmployeeAccessToken:企业微信员工Token时间没有失效,employeeAccessToken is: {}", corp.getEmployeeAccessToken());
			return corp.getEmployeeAccessToken();
		}

		getAccessToken(corp.getId(), corp.getEmployeeSecret(), json -> {
			corp.setEmployeeAccessToken(json.getString("access_token"));
			corp.setEmployeeAccessTokenExpiredTime(LocalDateTime.now().plusSeconds(json.getLong("expires_in")));
			jdbcSession.updateById(corp);
		});

		return corp.getEmployeeAccessToken();
	}

	/**
	 * 返回app的AccessToken
	 * @param suite
	 * @return
	 * @throws Exception
	 */
	public String geAppAccessToken(Suite suite) throws Exception {
		if(logger.isInfoEnabled()){
			logger.info("geAppAccessToken:企业微信App的Token时间 is: {}",suite.getAccessTokenExpiredTime());
		}
		if (valid(suite.getAccessTokenExpiredTime())) {
			logger.info("geAppAccessToken:企业微信App的Token时间没有失效,geAppAccessToken is: {}", suite.getAccessToken());
			return suite.getAccessToken();
		}

		getAccessToken(suite.getCorpId(), suite.getSecret(), json -> {
			suite.setAccessToken(json.getString("access_token"));
			suite.setAccessTokenExpiredTime(LocalDateTime.now().plusSeconds(json.getLong("expires_in")));
			jdbcSession.updateById(suite);
		});

		return suite.getAccessToken();
	}

	public Corp getCorpById(String id) {
		return jdbcSession.findById(Corp.class, id);
	}

	private void getAccessToken(final String corpid, final String secret, CallBack<JSONObject> call) throws Exception {
		if (Objects.nonEmpty(corpid) && Objects.nonEmpty(secret)) {
			if(logger.isInfoEnabled()){
				logger.info("getAccessToken:调用企业微信获取Token信息,corpid is {} and secret is {}",corpid,secret);
			}
			JSONObject jsonObject = httpClient.get("/cgi-bin/gettoken", http -> {
				http.addParam("corpid", corpid);
				http.addParam("corpsecret", secret);
			});

			if(logger.isInfoEnabled()){
				logger.info("getAccessToken:调用企业微信获取Token信息结果是{}",jsonObject.toJSONString());
			}
			if (jsonObject.getIntValue("errcode") == 0) {
				if(logger.isInfoEnabled()){
					logger.info("getAccessToken:执行企业微信获取Token信息回调");
				}
				call.call(jsonObject);
			}else{
				logger.warn("getAccessToken:低啊用企业微信获取Token信息失败,错误信息是 {}",jsonObject.toJSONString());
			}
		}
	}
	
	static boolean valid(LocalDateTime localDateTime) {
		if (Objects.isNull(localDateTime)) {
			return false;
		}
		
		return localDateTime.isAfter(LocalDateTime.now());
	}
	

}
